package fxification.async;
import fxification.java.TaskRunner;
import fxification.java.SimpleTaskRunner;
import java.lang.Throwable;
import fxification.java.JavaFXTaskContext;
import fxification.java.TaskRunnerContext;

/**
 * @author vladimir
 */

public class Task extends javafx.async.Task{
    var runner : TaskRunner = SimpleTaskRunner{}
    var context : TaskRunnerContext = new JavaFXTaskContext(this);

    public var work:function():Object on replace  {
        context.setTaskWork(work);
    }

    public var onStop:function() on replace {
        context.setStopTaskCallback(onStop);
    }

    public var onSucceeded:function(:Object) on replace {
        context.setTaskSucceededCallback(onSucceeded);
    }

    public var onFailure:function(:Throwable) on replace {
        context.setTaskFailedCallback(onFailure);
    }

    override public function start () : Void {
        runner.run(context);
    }

    override public function stop () : Void {
        runner.stop(context);
    }
}

public function runTask(work:function(), onSucceeded:function(:Object)):Task{
    def task:Task = Task{
        work:work
        onSucceeded:onSucceeded
        onFailure:function(e:Throwable){
            e.printStackTrace();
        }
    };
    task.start();
    return task;
}